package com.szxb.facebus.util.basics;

import android.os.CountDownTimer;

import com.szxb.facebus.db.entity.bean.QRScanMessage;
import com.szxb.facebus.util.rx.RxBus;

/**
 * 作者：Tangren on 2019-01-11
 * 包名：com.szxb.facebus.util.basics
 * 邮箱：996489865@qq.com
 * TODO:一句话描述
 */
public class CountTime {
    private volatile static CountTime instance = null;
    private volatile static long cnt = 0;

    private CountTime() {
    }

    public static CountTime getInstance() {
        if (instance == null) {
            synchronized (CountTime.class) {
                if (instance == null) {
                    instance = new CountTime();
                }
            }
        }
        return instance;
    }

    /**
     * 启动计时
     */
    public void startCnt(long millisInFuture) {
        if (timeCount != null) {
            timeCount.cancel();
            timeCount = null;
            canceled = true;
        }
        timeCount = new TimeTask(millisInFuture, 1000);
        if (canceled) {
            timeCount.start();
            canceled = false;
        }
    }

    /**
     * 停止计时
     */
    private void stopCnt() {
        if (canceled) {
            return;
        }
        if (timeCount != null) {
            timeCount.cancel();
        }
        RxBus.getInstance().send(new QRScanMessage(null, Constant.RECOVERY_VIEW));
        canceled = true;
    }

    private TimeTask timeCount;
    private boolean canceled = true;

    private class TimeTask extends CountDownTimer {

        public TimeTask(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            cnt = l;
        }

        @Override
        public void onFinish() {
            stopCnt();
        }
    }

}
